"""
消息相关路由
"""

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from typing import List

from database import get_db
from models.common import StandardResponse
from models.message import MessageCreate, MessageList
from services.auth_service import get_current_user
from services.message_service import MessageService

router = APIRouter(prefix="/messages", tags=["消息"])

@router.get("/list", response_model=StandardResponse, summary="获取消息列表")
async def get_messages_list(
    message_type: str = None,
    is_read: bool = None,
    page: int = 1,
    page_size: int = 20,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    获取用户消息列表
    
    - **message_type**: 消息类型（可选）
    - **is_read**: 是否已读（可选）
    - **page**: 页码
    - **page_size**: 每页数量
    """
    try:
        message_service = MessageService(db)
        messages_data = await message_service.get_user_messages(
            user_id=current_user["id"],
            message_type=message_type,
            is_read=is_read,
            page=page,
            page_size=page_size
        )
        
        return StandardResponse(
            success=True,
            message="获取消息列表成功",
            data=messages_data
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取消息列表失败: {str(e)}"
        )

@router.post("/read", response_model=StandardResponse, summary="标记消息已读")
async def mark_message_read(
    message_ids: List[int],
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    标记消息为已读
    
    - **message_ids**: 消息ID列表
    """
    try:
        message_service = MessageService(db)
        await message_service.mark_messages_read(
            user_id=current_user["id"],
            message_ids=message_ids
        )
        
        return StandardResponse(
            success=True,
            message="标记消息已读成功"
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"标记消息已读失败: {str(e)}"
        )

@router.get("/unread-count", response_model=StandardResponse, summary="获取未读消息数量")
async def get_unread_count(
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    获取用户未读消息数量
    """
    try:
        message_service = MessageService(db)
        unread_count = await message_service.get_unread_count(current_user["id"])
        
        return StandardResponse(
            success=True,
            message="获取未读消息数量成功",
            data={"unread_count": unread_count}
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"获取未读消息数量失败: {str(e)}"
        )

@router.delete("/{message_id}", response_model=StandardResponse, summary="删除消息")
async def delete_message(
    message_id: int,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
) -> StandardResponse:
    """
    删除消息
    
    - **message_id**: 消息ID
    """
    try:
        message_service = MessageService(db)
        await message_service.delete_message(
            message_id=message_id,
            user_id=current_user["id"]
        )
        
        return StandardResponse(
            success=True,
            message="删除消息成功"
        )
        
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"删除消息失败: {str(e)}"
        )